<!--
  结算单详情组件
  @description 查看结算单的详细信息
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1000px"
    :scroll="true"
    max-height="600px"
  >
    <div v-loading="loading">
      <!-- 结算单基本信息 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.settleOrder.basicInfo') }}</span>
          </div>
        </template>
        <el-descriptions :column="3" border v-if="settleOrderData">
          <el-descriptions-item :label="t('settle.settleOrder.settleNo')">
            {{ settleOrderData.settleNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.merchantNo')">
            {{ settleOrderData.merchantNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.merchantName')">
            {{ settleOrderData.merchantName }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.settleCycle')">
            <el-tag :type="getSettleCycleTagType(settleOrderData.settleCycle)">
              {{ settleCycleOptions[settleOrderData.settleCycle] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.settleDate')">
            {{ settleOrderData.settleDate }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.common.status')">
            <el-tag :type="getStatusTagType(settleOrderData.status)">
              {{ statusOptions[settleOrderData.status] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.settleAmount')">
            <span class="amount-text">¥{{ (settleOrderData.settleAmount / 100).toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.feeAmount')">
            <span class="fee-text">¥{{ (settleOrderData.feeAmount / 100).toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.actualAmount')">
            <span class="actual-text">¥{{ (settleOrderData.actualAmount / 100).toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.common.createTime')" :span="2">
            {{ formatDate(settleOrderData.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('settle.settleOrder.settleAccount')">
            {{ settleOrderData.settleAccount }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="t('settle.common.remark')"
            :span="3"
            v-if="settleOrderData.remark"
          >
            {{ settleOrderData.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 结算明细 -->
      <el-card class="mb-20px">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.settleOrder.settleDetails') }}</span>
          </div>
        </template>
        <el-table :data="settleDetails" border>
          <el-table-column
            :label="t('settle.settleOrder.orderNo')"
            align="center"
            prop="orderNo"
            width="200"
          />
          <el-table-column
            :label="t('settle.settleOrder.orderAmount')"
            align="center"
            prop="orderAmount"
            width="120"
          >
            <template #default="scope"> ¥{{ (scope.row.orderAmount / 100).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.settleOrder.feeAmount')"
            align="center"
            prop="feeAmount"
            width="100"
          >
            <template #default="scope"> ¥{{ (scope.row.feeAmount / 100).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.settleOrder.settleAmount')"
            align="center"
            prop="settleAmount"
            width="120"
          >
            <template #default="scope"> ¥{{ (scope.row.settleAmount / 100).toFixed(2) }} </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.settleOrder.orderTime')"
            align="center"
            prop="orderTime"
            width="180"
          >
            <template #default="scope">
              {{ formatDate(scope.row.orderTime) }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.settleOrder.channelType')"
            align="center"
            prop="channelType"
            width="120"
          >
            <template #default="scope">
              {{ channelTypeOptions[scope.row.channelType] || '-' }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('settle.common.remark')"
            align="center"
            prop="remark"
            min-width="150"
          >
            <template #default="scope">
              {{ scope.row.remark || '-' }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 明细分页 -->
        <Pagination
          :total="detailTotal"
          v-model:page="detailQueryParams.pageNo"
          v-model:limit="detailQueryParams.pageSize"
          @pagination="getSettleDetails"
          class="mt-20px"
        />
      </el-card>

      <!-- 操作记录 -->
      <el-card v-if="operationLogs.length > 0">
        <template #header>
          <div class="card-header">
            <span>{{ t('settle.settleOrder.operationLogs') }}</span>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="log in operationLogs"
            :key="log.id"
            :timestamp="formatDate(log.createTime)"
            placement="top"
          >
            <el-card>
              <h4>{{ log.operationType }}</h4>
              <p>{{ t('settle.settleOrder.operator') }}: {{ log.operatorName }}</p>
              <p v-if="log.remark">{{ t('settle.common.remark') }}: {{ log.remark }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import { getSettleOrderApi, getSettleStatisticsApi } from '@/api/settle/settleOrder'
import type {
  SettleOrderVO,
  SettleOrderDetailVO,
  SettleOrderLogVO,
  SettleOrderDetailPageReqVO
} from '@/api/settle/types'
import { SettleOrderStatusEnum, SettleCycleEnum, ChannelTypeEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'
import Pagination from '@/components/Pagination/index.vue'

defineOptions({ name: 'SettleOrderDetail' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)

// 结算单数据
const settleOrderData = ref<SettleOrderVO>()
const settleDetails = ref<SettleOrderDetailVO[]>([])
const detailTotal = ref(0)
const operationLogs = ref<SettleOrderLogVO[]>([])

// 明细查询参数
const detailQueryParams = reactive<SettleOrderDetailPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  settleOrderId: undefined
})

// 选项数据
const settleCycleOptions = {
  [SettleCycleEnum.DAILY]: t('settle.settleOrder.settleCycles.daily'),
  [SettleCycleEnum.WEEKLY]: t('settle.settleOrder.settleCycles.weekly'),
  [SettleCycleEnum.MONTHLY]: t('settle.settleOrder.settleCycles.monthly')
}

const statusOptions = {
  [SettleOrderStatusEnum.PENDING]: t('settle.settleOrder.statuses.pending'),
  [SettleOrderStatusEnum.CONFIRMED]: t('settle.settleOrder.statuses.confirmed'),
  [SettleOrderStatusEnum.REJECTED]: t('settle.settleOrder.statuses.rejected'),
  [SettleOrderStatusEnum.SETTLED]: t('settle.settleOrder.statuses.settled')
}

const channelTypeOptions = {
  [ChannelTypeEnum.HUIFU]: t('settle.settleOrder.channelTypes.huifu'),
  [ChannelTypeEnum.UNIONPAY]: t('settle.settleOrder.channelTypes.unionpay')
}

/**
 * 打开对话框
 */
const open = async (settleOrder: SettleOrderVO) => {
  dialogVisible.value = true
  dialogTitle.value = t('settle.settleOrder.detail') + ' - ' + settleOrder.settleNo
  loading.value = true

  try {
    // 获取结算单详情
    const data = await getSettleOrderApi(settleOrder.id)
    settleOrderData.value = data

    // 重置明细查询参数
    detailQueryParams.settleOrderId = settleOrder.id
    detailQueryParams.pageNo = 1

    // 获取结算明细
    await getSettleDetails()

    // 获取操作记录
    await getOperationLogs(settleOrder.id)
  } catch (error) {
    console.error('获取结算单详情失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 获取结算明细
 */
const getSettleDetails = async () => {
  try {
    const data = await getSettleOrderDetailsApi(detailQueryParams)
    settleDetails.value = data.list
    detailTotal.value = data.total
  } catch (error) {
    console.error('获取结算明细失败:', error)
  }
}

/**
 * 获取操作记录
 */
const getOperationLogs = async (settleOrderId: number) => {
  try {
    const data = await getSettleOrderLogsApi(settleOrderId)
    operationLogs.value = data
  } catch (error) {
    console.error('获取操作记录失败:', error)
  }
}

// 标签类型获取函数
const getSettleCycleTagType = (cycle: number) => {
  const cycleMap = {
    [SettleCycleEnum.DAILY]: 'primary',
    [SettleCycleEnum.WEEKLY]: 'success',
    [SettleCycleEnum.MONTHLY]: 'warning'
  }
  return cycleMap[cycle] || ''
}

const getStatusTagType = (status: number) => {
  const statusMap = {
    [SettleOrderStatusEnum.PENDING]: 'warning',
    [SettleOrderStatusEnum.CONFIRMED]: 'primary',
    [SettleOrderStatusEnum.REJECTED]: 'danger',
    [SettleOrderStatusEnum.SETTLED]: 'success'
  }
  return statusMap[status] || ''
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.mt-20px {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-text {
  color: #409eff;
  font-weight: bold;
}

.fee-text {
  color: #e6a23c;
  font-weight: bold;
}

.actual-text {
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}
</style>
